from dataclasses import dataclass
import json
import os
from typing import Any

@dataclass
class Config:
    '''Configuration data class for application settings'''
    font: str = 'Unknown'  # Selected font family
    admin_launch: bool | str = 'Unknown'  # Admin launch preference
    fps: int = 60  # Frames per second for animation
    island_height_offset: int = 50  # Vertical position offset
    legacy_animation: bool = True
    api_key: str = 'Unknown'

# Global configuration instance
config_instance = Config()

# Initialize configuration file if it doesn't exist
if not os.path.exists('config.json'):
    with open('config.json', 'w', encoding='utf-8') as f:
        json.dump(config_instance.__dict__, f, indent=4)
else:
    # Load existing configuration
    with open('config.json', 'r', encoding='utf-8') as f:
        try:
            data_dict = json.load(f)
        except:
            # Config file is corrupted, recreate it
            with open('config.json', 'w', encoding='utf-8') as f:
                json.dump(config_instance.__dict__, f, indent=4)
        else:
            # Check if config structure matches current version
            if len(config_instance.__dict__.keys()) != len(data_dict.keys()):
                # Config is outdated, update it
                with open('config.json', 'w', encoding='utf-8') as f:
                    json.dump(config_instance.__dict__, f, indent=4)

def saveConfig() -> None:
    '''Save current configuration to file'''
    data_dict = config_instance.__dict__
    with open('config.json', 'w', encoding='utf-8') as f:
        json.dump(data_dict, f, indent=4)

def loadConfig() -> dict[str, Any]:
    '''Load configuration from file and update global instance'''
    with open('config.json', 'r', encoding='utf-8') as f:
        data_dict = json.load(f)
    config_instance.__dict__.update(data_dict)
    return data_dict